package com.jiepos.mpos.biz.service.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jiepos.mpos.common.constant.DBConstant;
import com.jiepos.mpos.common.constant.DBConstant.Table;
import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.common.dao.ServiceParamDao;
import com.jiepos.mpos.common.entity.App_Service_InfEntity;
import com.jiepos.mpos.common.entity.App_Service_ParamEntity;
import com.jiepos.mpos.core.entity.Pagination;
import com.jiepos.mpos.core.service.BaseService;
import com.jiepos.mpos.core.util.IDFactoryUtil;
import com.jiepos.mpos.core.util.StringUtils;

/**
 * 业务参数维护Service
 * @author Zhao.Jinkui
 * @version 1.0
 * @ProjectName: mpos
 * @Package com.jiepos.mpos.biz.service.service
 * @ClassName ServiceParamService
 * @history
 * @UpdateRemark []
 * @since 2017/9/24
 */
@Service
public class ServiceParamService extends BaseService{

    @Autowired
    private ServiceParamDao serviceParamDao;

    /**
     * 根据条件分页查询业务参数信息
     * @param pagination 分页组件
     * @param entity 查询参数实体
     * @param appServiceInfEntity 查询业务实体
     * @return
     */
    public Map findByCondition(Pagination pagination, App_Service_ParamEntity entity,App_Service_InfEntity appServiceInfEntity){

        StringBuffer sqlBuf =  getInitSql("P").append(", ");
        sqlBuf.append("  P.SERVICE_PARAM_UUID AS UUID, ")
                .append("        P.SERVICE_UUID, ")
                .append("        P.PARAM_NO, ")
                .append("        P.PARAM_NAME, ")
                .append("        P.PARAM_ST || '-' || ")
                .append("        (SELECT CODE_DESC ")
                .append("           FROM "+ DBConstant.Table.T_APP_CODE_LIST)
                .append("          WHERE CODE_TP =  '"+ DBConstant.Code.SERVICE_ST+"'")
                .append("            AND P.PARAM_ST = CODE_VAL) AS PARAM_ST, ")
                .append("        P.REC_ID, ")
                .append("        P.REC_ST, ")
                .append("        P.LAST_OPER_IN, ")
                .append("        I.SERVICE_NO, ")
                .append("        I.SERVICE_NAME, ")
                .append("        I.SERVICE_ST || '-' || ")
                .append("        (SELECT CODE_DESC ")
                .append("           FROM "+ DBConstant.Table.T_APP_CODE_LIST)
                .append("          WHERE CODE_TP =  '"+ DBConstant.Code.SERVICE_ST+"'")
                .append("            AND I.SERVICE_ST = CODE_VAL) AS SERVICE_ST ")
                .append("   FROM "+DBConstant.Table.T_APP_SERVICE_PARAM+" P ")
                .append("   LEFT JOIN "+DBConstant.Table.T_APP_SERVICE_INF+" I ")
                .append("     ON P.SERVICE_UUID = I.SERVICE_UUID ")
                .append("  WHERE 1 = 1 ");
        //参数集合
        List<String> params = new ArrayList<>();
        if(!StringUtils.isBlank(appServiceInfEntity.getService_no())){
            sqlBuf.append("   AND I.SERVICE_NO LIKE ? ");
            params.add("%"+appServiceInfEntity.getService_no()+"%");
        }
        if(!StringUtils.isBlank(appServiceInfEntity.getService_name())){
            sqlBuf.append("   AND I.SERVICE_NAME LIKE ? ");
            params.add("%"+appServiceInfEntity.getService_name()+"%");
        }
        if(!StringUtils.isBlank(appServiceInfEntity.getService_st())){
            sqlBuf.append("   AND I.SERVICE_ST = ? ");
            params.add(appServiceInfEntity.getService_st());
        }
        if(!StringUtils.isBlank(entity.getParam_no())){
            sqlBuf.append("   AND P.PARAM_NO LIKE ? ");
            params.add("%"+entity.getParam_no()+"%");
        }
        if(!StringUtils.isBlank(entity.getParam_name())){
            sqlBuf.append("   AND P.PARAM_NAME LIKE ? ");
            params.add("%"+entity.getParam_name()+"%");
        }
        if(!StringUtils.isBlank(entity.getParam_st())){
            sqlBuf.append("   AND P.PARAM_ST = ? ");
            params.add(entity.getParam_st());
        }

        pagination.queryString = sqlBuf.toString();
        pagination = this.getOrderSql(pagination,"P");
        //执行查询
        return serviceParamDao.getPaginationMap(pagination,"",params);
    }

    /**
     * 根据UUID加载唯一业务参数信息
     * @param
     * @return
     */
    public App_Service_ParamEntity findByUUID(String serviceParam_uuid){
        return serviceParamDao.findByParam("service_param_uuid", serviceParam_uuid);
    }

    /**
     * 保存业务参数(新增、修改)
     * @param entity
     * @param map
     */
    public void saveServiceParam(App_Service_ParamEntity entity,Map map){
        //以是否有uuid来区分操作
        if (!StringUtils.isBlank(entity.getService_param_uuid())) {
            //更新
            entity = (App_Service_ParamEntity) this.saveCommonData(entity,map,"update");
            List noChangeList = new ArrayList();
            noChangeList.add("service_param_uuid");
            noChangeList.add("rec_crt_ts");
            serviceParamDao.update(entity,noChangeList);
        }else{
            //新增
            entity = (App_Service_ParamEntity) this.saveCommonData(entity, map, null);
            entity.setService_param_uuid(IDFactoryUtil.getUUID());
            serviceParamDao.save(entity);
        }

    }

    /**
     * 启用、冻结业务参数
     * @param serviceParamSt
     * @param serviceParam_uuids
     * @param loginUser
     */
    public void updateServiceParamSt(String serviceParamSt, String serviceParam_uuids, Map loginUser){
        serviceParamDao.updateByIds("service_param_uuid", serviceParam_uuids, serviceParamSt,
                String.valueOf(loginUser.get(SystemConstant.SESSION_LOGIN_USER)));
    }

    /**
     * 检查业务参数是否存在(编号)
     * @param entity
     * @return
     */
    public String checkService(App_Service_ParamEntity entity){
        //如果uuid不是空 那么说明是修改操作，那么不做限制
        if(StringUtils.isBlank(entity.getService_param_uuid())){
            //新增操作，那么判断 业务参数编号是否重复
            StringBuffer sqlBuf = new StringBuffer();
            sqlBuf.append(" SELECT SERVICE_PARAM_UUID ")
                    .append("   FROM ")
                    .append(DBConstant.Table.T_APP_SERVICE_PARAM)
                    .append("  WHERE 1=2 ");

            //参数集合
            List<String> params = new ArrayList<>();
            if(!StringUtils.isBlank(entity.getParam_no())){
                sqlBuf.append("  OR PARAM_NO = ? ");
                params.add(entity.getParam_no());
            }
            if(params.size() > 0){
                List list = serviceParamDao.queryForList(sqlBuf.toString(),params);
                if(list!=null && list.size() > 0){
                    //有重复的编号,返回 error
                    return SystemConstant.ERROR;
                }
            }
        }
        return SystemConstant.SUCCESS;
    }

    /**
     * 获取业务参数数据
     * @param service_uuid 业务uuid
     * @return
     */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<Map<String, Object>> findAllServiceParams(String service_uuid) {
		StringBuffer sqlSb = new StringBuffer();
		sqlSb.append("select service_param_uuid, param_no||'-'||param_name as param_name from ");
		sqlSb.append(Table.T_APP_SERVICE_PARAM);
		sqlSb.append(" where 1=1 ");
		List list = new ArrayList();
		if (!StringUtils.isBlank(service_uuid)) {
			sqlSb.append("and service_uuid = ?");
			list.add(service_uuid);
		}
		List<Map<String, Object>> result = serviceParamDao.queryForList(sqlSb.toString(), list);
		Map<String, Object> topMap = new HashMap<String, Object>();
		topMap.put("SERVICE_PARAM_UUID", "");
		topMap.put("PARAM_NAME", "---请选择---");
		result.add(0, topMap);
		return result;
	}
	
	
	/**
	 * 根据参数编号查询
	 * @param param_no
	 * @return
	 */
	public String findUuidByNo(String param_no){
    	if (StringUtils.isBlank(param_no) || param_no.equals("undefined")) {
			return "";
		}
    	App_Service_ParamEntity entity = serviceParamDao.findByParam("param_no", param_no);   
    	if(entity!=null){
    		return entity.getService_param_uuid();
    	}
        return "";
    }

}
